package proxy.dynamicProxy.customeizeJdkProxy;

import org.apache.commons.io.FileUtils;
import proxy.staticProxy.Car;
import proxy.staticProxy.MoveAble;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Proxy {
    public static Object newProxyInstance(Class infce, InvocationHandler h) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        String rt = "\r\n";
        String methodStr = "";
        for (Method m : infce.getMethods()) {
            methodStr += "	@Override" + rt +
                    "	public void " + m.getName() + "() {" + rt +
                    "  try{" + rt +
                    "  Method md = " + infce.getName() + ".class.getMethod(\""
                    + m.getName() + "\");" + rt +
                    "  h.invoke(this,md);" +rt+
                    "  }catch(Exception e){ e.printStackTrace();}" + rt +
                    "	}" ;
        }

        String str =
        "package proxy.dynamicProxy.customeizeJdkProxy;" + rt +
         "import proxy.dynamicProxy.customeizeJdkProxy.InvocationHandler;"+ rt +
         "import java.lang.reflect.Method;" + rt +
        "public class $Proxy0 implements " + infce.getName() +"{" + rt +
        "   private InvocationHandler h;" + rt +
        "   public $Proxy0(InvocationHandler h) {" + rt +
        "       this.h = h;" + rt +
        "   }" + rt +
        methodStr + rt +
        "}";

        //产生代理类的java文件
        String fileName = System.getProperty("user.dir") + "/bin/proxy/dynamicProxy/customeizeJdkProxy/$Proxy0.java";
        File file = new File(fileName);
        FileUtils.writeStringToFile(file, str);

        // 编译
        // 拿到编译器
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 文件管理者
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        //获取文件
        Iterable units = fileManager.getJavaFileObjects(fileName);
        //编译任务
        JavaCompiler.CompilationTask t = compiler.getTask(null, fileManager, null, null, null, units);
        //进行编译
        t.call();
        fileManager.close();


        //load到内存
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        Class c = cl.loadClass("proxy.dynamicProxy.customeizeJdkProxy.$Proxy0");

        Constructor ctr = c.getConstructor(InvocationHandler.class);
        return ctr.newInstance(h);
    }
}
